<template>
  <div class="main">
    <div class="content-container"
      v-if="Store.$state.AITeach.Step1.content.length !== 0 && Store.$state.AITeach.Step1.state === 1">
      <!-- 逐字显示内容 -->
      <div v-if="shouldTypewriter">
        <div v-for="(item, index) in data" :key="index" class="content-item"
          v-show="typewriterTexts[index]?.length > 0">
          <p class="content-text">
            <template v-for="(char, charIndex) in (typewriterTexts[index] || '')" :key="charIndex">
              <span :class="{
                'char': true,
                'bold-first-sentence': isFirstSentence(charIndex, typewriterTexts[index])
              }">
                {{ char }}
              </span>
            </template>
            <button v-if="allTyped" @click="startEdit(index)" class="edit-btn">编辑</button>
          </p>
        </div>
      </div>

      <!-- 直接显示完整内容 -->
      <div v-else>
        <div v-for="(item, index) in data" :key="index" class="content-item">
          <p class="content-text" v-if="!editingIndexes.includes(index)">
            <template v-for="(sentence, sentenceIndex) in splitIntoSentences(item)" :key="sentenceIndex">
              <span :class="{ 'bold-sentence': sentenceIndex === 0 }">
                {{ sentence }}
              </span>
            </template>
            <button @click="startEdit(index)" class="edit-btn">编辑</button>
          </p>
          <div v-else class="edit-container">
            <textarea 
              v-model="editTexts[index]" 
              class="edit-textarea"
              ref="editTextareas"
            ></textarea>
            <div class="edit-buttons">
              <button @click="saveEdit(index)" class="save-btn">保存</button>
              <button @click="cancelEdit(index)" class="cancel-btn">取消</button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="Store.$state.AITeach.Step1.content.length === 0 && Store.$state.AITeach.Step1.state === 1">
        <Wait />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useCounterStore } from '@/stores/counter';
const Store = useCounterStore();
import axios from 'axios'

import Wait from '../Wait.vue';
import Null from '../Null.vue'

const data = ref<string[]>([]);
const currentIndex = ref(0);
const typewriterTexts = ref<string[]>([]);
const isLoading = ref(false);
const isDataLoaded = ref(false);
const shouldTypewriter = ref(true);
const allTyped = ref(false);
const editingIndexes = ref<number[]>([]);
const editTexts = ref<string[]>([]);
const editTextareas = ref<HTMLTextAreaElement[]>([]);

// 判断是否是第一句话的第一个字符
function isFirstSentence(charIndex: number, text: string): boolean {
  if (!text) return false;
  const firstPeriodIndex = text.indexOf('.');
  return firstPeriodIndex === -1 || charIndex <= firstPeriodIndex;
}

// 将文本分割成句子
function splitIntoSentences(text: string): string[] {
  return text.split(/(?<=\.)\s+/);
}

const emit = defineEmits<{
  (e: 'ToNextStep', param: number): void;
}>();

onMounted(async () => {
  console.log('Step1')
  if (Store.$state.AITeach.Step1.content.length === 0) {
    isLoading.value = true;
    try {
      const response = await axios({
        url: "https://m1.apifoxmock.com/m1/5997017-0-default/teacher/design/knowledge",
        method: "POST",
        data: {
          userId: localStorage.getItem('userId'),
          text: Store.$state.AIClassQuestion,
        }
      });

      if (response.data.code === 200) {
        Store.addAIteachStep1(response.data.data.analysis);
        data.value = Store.$state.AITeach.Step1.content;
        editTexts.value = [...data.value]; // 初始化编辑文本
        isDataLoaded.value = true;

        if (shouldTypewriter.value && data.value.length > 0) {
          typeText(data.value[0], 0);
        } else {
          allTyped.value = true;
        }
      } else {
        console.error(response.data.code);
        alert('网络错误，显示失败');
      }
    } catch (error) {
      alert("出现" + error + "错误，请重新操作");
    } finally {
      isLoading.value = false;
    }
  } else {
    data.value = Store.$state.AITeach.Step1.content;
    editTexts.value = [...data.value]; // 初始化编辑文本
    isDataLoaded.value = true;
    shouldTypewriter.value = false;
    allTyped.value = true;
    // emit('ToNextStep', 2);
  }
});

// 开始编辑
function startEdit(index: number) {
  if (!editingIndexes.value.includes(index)) {
    editingIndexes.value.push(index);
    editTexts.value[index] = data.value[index];
    nextTick(() => {
      if (editTextareas.value[index]) {
        editTextareas.value[index].focus();
      }
    });
  }
}

// 保存编辑
function saveEdit(index: number) {
  data.value[index] = editTexts.value[index];
  Store.$state.AITeach.Step1.content[index] = editTexts.value[index]; // 更新store
  editingIndexes.value = editingIndexes.value.filter(i => i !== index);
}

// 取消编辑
function cancelEdit(index: number) {
  editingIndexes.value = editingIndexes.value.filter(i => i !== index);
}

//逐字显示
function typeText(text: string, index: number) {
  if (typewriterTexts.value.length <= index) {
    typewriterTexts.value = [...typewriterTexts.value, ''];
  }
  
  let currentText = '';
  const interval = setInterval(() => {
    if (currentText.length < text.length) {
      currentText = text.substring(0, currentText.length + 1);
      typewriterTexts.value[index] = currentText;
      typewriterTexts.value = [...typewriterTexts.value];
    } else {
      clearInterval(interval);
      if (index < data.value.length - 1) {
        currentIndex.value = index + 1;
        typeText(data.value[currentIndex.value], currentIndex.value);
      } else {
        shouldTypewriter.value = false;
        allTyped.value = true;
        setTimeout(() => {
          emit('ToNextStep', 2);
        }, 1000);
      }
    }
  }, 50);
}
</script>

<style scoped>
.content-container {
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.content-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #409EFF;
  position: relative;
}

.content-text {
  font-size: 16px;
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
}

.char {
  opacity: 0;
  animation: fadeIn 0.1s forwards;
}

.bold-first-sentence,
.bold-sentence {
  font-weight: bold;
  color: #2c3e50;
}

.edit-btn {
  position: absolute;
  right: 10px;
  top: 10px;
  background: #409EFF;
  color: white;
  border: none;
  padding: 2px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn:hover {
  background: #66b1ff;
}

.edit-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.edit-textarea {
  width: 100%;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
  font-size: 14px;
}

.edit-textarea:focus {
  outline: none;
  border-color: #409EFF;
}

.edit-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.save-btn {
  background: #409EFF;
  color: white;
  border: none;
  padding: 5px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background: #66b1ff;
}

.cancel-btn {
  background: #f56c6c;
  color: white;
  border: none;
  padding: 5px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background: #f78989;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}
</style>